/*
 * For com.royal.art
 * Copyright [2015/11/15] By FCHEN
 */
package com.manage.controller;

import com.beans.Dept;
import com.beans.SysMenu;
import com.beans.SysRole;
import com.beans.SysUser;
import com.beans.page.PageList;
import com.commons.PwdUtils;
import com.commons.util.StringUtil;
import com.manage.util.UserUtils;
import com.services.DeptService;
import com.services.SysRoleMenuService;
import com.services.SysRoleService;
import com.services.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * SysUserController
 *
 * @author FCHEN
 * @date 2015/11/15
 */
@Controller
@RequestMapping("sysuser")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private SysRoleMenuService roleMenuService;

    @ModelAttribute("sysUser")
    public SysUser get(@RequestParam(required = false) Long id) {
        if (id != null) {
            return UserUtils.get(id);
        } else {
            return new SysUser();
        }
    }

    /**
     * 查询列表
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = {"", "/", "list"})
    public String list(SysUser sysUser, HttpServletRequest request) {
        List<Dept> deptList = deptService.queryList(new Dept());

        request.setAttribute("sysUser", sysUser);
        request.setAttribute("deptList", deptList);

        return "sys/sysuser/list";
    }

    /**
     * 异步获取list资源
     *
     * @param pageList
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping("asynList")
    @ResponseBody
    public PageList asynList(PageList pageList, SysUser sysUser) {

        return sysUserService.queryPageByUser(pageList, sysUser);
    }

    /**
     * 异步获取Menu list资源
     *
     * @return
     */
    @RequestMapping("menuList")
    @ResponseBody
    public List<SysMenu> asynMenuList(@RequestParam Long id) {
        return UserUtils.getMenuListShow(id);
    }

    /**
     * 新增修改
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:add")
    @RequestMapping(value = {"add"}, method = RequestMethod.GET)
    public String add(SysUser sysUser, Model model) {
        //添加用户
        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("sysUser", sysUser);
        SysRole sysRole = sysRoleService.queryById(Long.valueOf(UserUtils.getUser().getUserRole()));

        List<Dept> list = new ArrayList<>();
        if (sysRole.getRoleId() == 4
                || sysRole.getRoleId() == 6
                || sysRole.getRoleId() == 7 ||
                sysRole.getRoleId() == 8) {//非管理员和总经理
            list.add(deptService.queryById(UserUtils.getUser().getDeptId()));
        } else {
            list.addAll(deptService.findAllList(new Dept()));
        }
        model.addAttribute("depts", list);

        List<SysRole> rlist = new ArrayList<>();
        if (sysRole.getRoleId() == 2 || sysRole.getRoleId() == 1) {//管理员
            rlist.add(sysRoleService.queryById(3));
            rlist.add(sysRoleService.queryById(4));
            rlist.add(sysRoleService.queryById(6));
            rlist.add(sysRoleService.queryById(7));
            rlist.add(sysRoleService.queryById(8));
        } else if (sysRole.getRoleId() == 3) {//总经理
            rlist.add(sysRoleService.queryById(4));
            rlist.add(sysRoleService.queryById(6));
            rlist.add(sysRoleService.queryById(7));
            rlist.add(sysRoleService.queryById(8));
        } else if (sysRole.getRoleId() == 7) {//店长
            rlist.add(sysRoleService.queryById(4));
            rlist.add(sysRoleService.queryById(6));
            rlist.add(sysRoleService.queryById(8));
        } else if (sysRole.getRoleId() == 6) {//助理
            rlist.add(sysRoleService.queryById(8));
        }
        model.addAttribute("allRoles", rlist);
        model.addAttribute("menuList", rlist.size() > 0 ? UserUtils.getMenuListShow(rlist.get(0).getRoleId())
                : new ArrayList<>());
        return "sys/sysuser/add";
    }

    /**
     * 新增修改
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = {"edit"}, method = RequestMethod.GET)
    public String edit(SysUser sysUser, Model model) {
        //编辑的时候不允许修改门店和角色
        sysUser = sysUserService.queryById(sysUser.getUserId());

        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("sysUser", sysUser);

        List<Dept> list = new ArrayList<>();
        list.addAll(deptService.findAllList(new Dept()));
        model.addAttribute("depts", list);

        List<SysRole> rlist = new ArrayList<>();
        rlist.addAll(sysRoleService.queryList(new SysRole()));
        model.addAttribute("allRoles", rlist);

        model.addAttribute("menuList", UserUtils.getMenuListShow(Long.parseLong(sysUser.getUserRole())));
        return "sys/sysuser/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String save(SysUser sysUser) {
        sysUser.setCreateBy(UserUtils.getUser().getUserId());
        sysUser.setUpdateBy(UserUtils.getUser().getUserId());
        // 如果新密码为空，则不更换密码
        if (StringUtil.isNotBlank(sysUser.getPassword())) {
            if (sysUser.getSalt() == null || sysUser.getSalt().isEmpty()) {
                sysUser.setSalt(PwdUtils.getSalt());
            }
            sysUser.setPassword(PwdUtils.saltPwd(sysUser.getPassword(), sysUser.getSalt()));
        }
        UserUtils.clearCache(sysUser);

        if (sysUser.getHeadPhoto() == null) {
            sysUser.setHeadPhoto("default_header.png");
        }
        if (sysUser.getUserId() == null) {
            sysUserService.add(sysUser);
        } else {
            sysUserService.update(sysUser);
        }

        // 更新用户与菜单关联
        sysUserService.deleteUserOfMenu(sysUser);
        if (sysUser.getMenuIdList().size() > 0) {
            sysUserService.addUserOfMenu(sysUser);
        }

        // 清除当前用户缓存
        if (sysUser.getMobile().equals(UserUtils.getUser().getMobile())) {
            UserUtils.clearCache();
        }
        //TODO  成功失败结果页面
        return "redirect:list";
    }

    @RequiresPermissions("sys:user:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Long id, HttpServletRequest request) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(id);
        sysUser.setUpdateBy(UserUtils.getUser().getUserId());
        int result = sysUserService.delete(sysUser);
        //TODO  成功失败结果页面
        return result;
    }

    /**
     * 验证登录名是否有效
     *
     * @param oldAccount
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkAccount", method = RequestMethod.POST)
    public Boolean checkAccount(String oldAccount, String mobile) {
        if (mobile != null && mobile.equals(oldAccount)) {
            return Boolean.TRUE;
        } else if (mobile != null && sysUserService.queryUserByAccount(mobile) == null) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


}
